package top.lshaci.learning.springboot.jpaquerydsl.core;

import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.EntityPathBase;
import lombok.Data;

import static java.util.Optional.ofNullable;

/**
 * AbstractDslQuery
 *
 * @author liangxu
 */
@Data
public abstract class AbstractDslQuery implements DslQuery {

    /**
     * 页码
     */
    @DslCondition(ignore = true)
    private Integer page;

    /**
     * 每页条数
     */
    @DslCondition(ignore = true)
    private Integer size;

    /**
     * 排序方式
     */
    @DslCondition(ignore = true)
    private String sort;

    /**
     * 页码
     *
     * @return 页码
     */
    protected int page() {
        return ofNullable(this.page).filter(p -> p > 0).orElse(1) - 1;
    }

    /**
     * 数据条数
     *
     * @return 数据条数
     */
    protected int size() {
        return ofNullable(this.size).filter(s -> s > 0).orElse(10);
    }

    @Override
    public final int offset() {
        return page() * size();
    }

    @Override
    public final int limit() {
        return size();
    }

    @Override
    public OrderSpecifier<?>[] sort() {
        return DslOrderUtil.sort(this.sort, fromObj());
    }

    @Override
    public <Q extends EntityPathBase<?>> Q fromObj() {
        return DslFromUtil.fromObj(this);
    }
}
